package pinkblob.servlet;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pinkblob.entity.DbFile;



public class Download extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		
		String id = request.getParameter("id");
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("PinkBlob2");
		EntityManager em = emf.createEntityManager();
		
		
		Query q = em.createQuery("Select f FROM DbFile f WHERE f.Id = :id");
		q.setParameter("id", Integer.parseInt(id));
		
		DbFile file = (DbFile)q.getSingleResult();
		
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setContentLength(file.getFile().length);
		response.setHeader("Content-Disposition", "filename=" + file.getFilename());
		ServletOutputStream stream = response.getOutputStream();
		stream.write(file.getFile());
		stream.flush();
		stream.close();
	}
	
}
